"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import { Separator } from "@/components/ui/separator"
import { Badge } from "@/components/ui/badge"
import {
  ArrowLeft,
  User,
  Bell,
  Palette,
  Shield,
  CreditCard,
  Globe,
  Moon,
  Sun,
  Smartphone,
  Mail,
  MessageSquare,
  Lock,
  Key,
  Trash2,
  Download,
} from "lucide-react"

export default function SettingsPage() {
  const router = useRouter()
  const [activeSection, setActiveSection] = useState("general")
  const [currentUser, setCurrentUser] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [settings, setSettings] = useState({
    // 通用设置
    name: "",
    email: "",
    phone: "",
    bio: "",
    language: "zh-CN",
    timezone: "Asia/Shanghai",

    // 通知设置
    pushNotifications: true,
    emailNotifications: true,
    smsNotifications: false,
    marketingEmails: true,
    weeklyDigest: true,

    // 外观设置
    theme: "system",
    fontSize: "medium",
    compactMode: false,

    // 隐私设置
    profileVisibility: "public",
    showEmail: false,
    showPhone: false,
    dataCollection: true,

    // 安全设置
    twoFactorAuth: false,
    loginAlerts: true,

    // 订阅设置
    plan: "free",
    autoRenew: true,
  })

  const sections = [
    { id: "general", name: "通用", icon: User },
    { id: "notifications", name: "通知", icon: Bell },
    { id: "appearance", name: "外观", icon: Palette },
    { id: "privacy", name: "隐私", icon: Shield },
    { id: "security", name: "安全", icon: Lock },
    { id: "billing", name: "计费", icon: CreditCard },
  ]

  const handleSettingChange = (key, value) => {
    setSettings((prev) => ({ ...prev, [key]: value }))
  }

  // 检查用户登录状态并加载设置
  useEffect(() => {
    const user = localStorage.getItem('currentUser')
    if (!user) {
      alert('请先登录后使用此功能')
      router.push('/login')
      return
    }
    const userData = JSON.parse(user)
    setCurrentUser(userData)
    
    // 加载用户设置，优先使用保存的设置，否则使用默认值
    const savedSettings = localStorage.getItem(`settings_${userData.id}`)
    if (savedSettings) {
      setSettings(JSON.parse(savedSettings))
    } else {
      // 使用用户数据初始化设置
      setSettings(prev => ({
        ...prev,
        name: userData.name || '',
        email: userData.email || '',
        phone: userData.phone || '',
        bio: userData.bio || '',
      }))
    }
    setIsLoading(false)
  }, [router])

  const handleSave = () => {
    if (!currentUser) return
    
    // 保存设置到localStorage
    localStorage.setItem(`settings_${currentUser.id}`, JSON.stringify(settings))
    
    // 更新currentUser中的基本信息
    const updatedUser = {
      ...currentUser,
      name: settings.name,
      email: settings.email,
      phone: settings.phone,
      bio: settings.bio
    }
    localStorage.setItem('currentUser', JSON.stringify(updatedUser))
    setCurrentUser(updatedUser)
    
    // 同时更新registeredUsers中的数据
    const registeredUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
    const userIndex = registeredUsers.findIndex((u: any) => u.id === currentUser.id)
    if (userIndex !== -1) {
      registeredUsers[userIndex] = { ...registeredUsers[userIndex], ...updatedUser }
      localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers))
    }
    
    alert('设置保存成功！')
    console.log("保存设置:", settings)
  }

  const handleExportData = () => {
    // 导出数据
    console.log("导出用户数据")
    alert("数据导出已开始，请查看邮箱")
  }

  const handleDeleteAccount = () => {
    if (confirm("确定要删除账户吗？此操作不可恢复。")) {
      console.log("删除账户")
      alert("账户删除请求已提交")
    }
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/30 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-4 border-slate-300 border-t-slate-600 rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-slate-600">加载设置...</p>
        </div>
      </div>
    )
  }

  if (!currentUser) {
    return null
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/30">
      {/* 顶部导航 */}
      <header className="bg-white/80 backdrop-blur-xl border-b border-slate-200/50 sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-6 py-4">
          <div className="flex items-center space-x-4">
            <Button variant="ghost" onClick={() => router.back()}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              返回
            </Button>
            <div className="flex items-center space-x-2">
              <Shield className="w-6 h-6 text-blue-600" />
              <h1 className="text-xl font-semibold text-slate-900">设置</h1>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-6 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          {/* 左侧导航 */}
          <div className="lg:col-span-1">
            <Card className="bg-white/70 backdrop-blur-sm border-0 shadow-sm">
              <CardContent className="p-4">
                <nav className="space-y-2">
                  {sections.map((section) => {
                    const Icon = section.icon
                    return (
                      <button
                        key={section.id}
                        onClick={() => setActiveSection(section.id)}
                        className={`w-full flex items-center space-x-3 px-3 py-2 rounded-lg text-left transition-colors ${
                          activeSection === section.id
                            ? "bg-blue-100 text-blue-700"
                            : "text-slate-600 hover:bg-slate-100"
                        }`}
                      >
                        <Icon className="w-4 h-4" />
                        <span>{section.name}</span>
                      </button>
                    )
                  })}
                </nav>
              </CardContent>
            </Card>
          </div>

          {/* 右侧内容 */}
          <div className="lg:col-span-3">
            <Card className="bg-white/70 backdrop-blur-sm border-0 shadow-sm">
              <CardContent className="p-8">
                {/* 通用设置 */}
                {activeSection === "general" && (
                  <div className="space-y-6">
                    <div>
                      <h2 className="text-2xl font-semibold text-slate-900 mb-6">通用设置</h2>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <div>
                        <Label htmlFor="name">姓名</Label>
                        <Input
                          id="name"
                          value={settings.name}
                          onChange={(e) => handleSettingChange("name", e.target.value)}
                          className="mt-2"
                        />
                      </div>
                      <div>
                        <Label htmlFor="email">邮箱</Label>
                        <Input
                          id="email"
                          type="email"
                          value={settings.email}
                          onChange={(e) => handleSettingChange("email", e.target.value)}
                          className="mt-2"
                        />
                      </div>
                      <div>
                        <Label htmlFor="phone">手机号</Label>
                        <Input
                          id="phone"
                          value={settings.phone}
                          onChange={(e) => handleSettingChange("phone", e.target.value)}
                          className="mt-2"
                        />
                      </div>
                      <div>
                        <Label htmlFor="language">语言</Label>
                        <Select
                          value={settings.language}
                          onValueChange={(value) => handleSettingChange("language", value)}
                        >
                          <SelectTrigger className="mt-2">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="zh-CN">简体中文</SelectItem>
                            <SelectItem value="en-US">English</SelectItem>
                            <SelectItem value="ja-JP">日本語</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>

                    <div>
                      <Label htmlFor="bio">个人简介</Label>
                      <Textarea
                        id="bio"
                        value={settings.bio}
                        onChange={(e) => handleSettingChange("bio", e.target.value)}
                        className="mt-2"
                        rows={3}
                      />
                    </div>
                  </div>
                )}

                {/* 通知设置 */}
                {activeSection === "notifications" && (
                  <div className="space-y-6">
                    <div>
                      <h2 className="text-2xl font-semibold text-slate-900 mb-6">通知设置</h2>
                    </div>

                    <div className="space-y-4">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                          <Smartphone className="w-5 h-5 text-slate-600" />
                          <div>
                            <p className="font-medium text-slate-900">推送通知</p>
                            <p className="text-sm text-slate-600">接收应用推送通知</p>
                          </div>
                        </div>
                        <Switch
                          checked={settings.pushNotifications}
                          onCheckedChange={(checked) => handleSettingChange("pushNotifications", checked)}
                        />
                      </div>

                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                          <Mail className="w-5 h-5 text-slate-600" />
                          <div>
                            <p className="font-medium text-slate-900">邮件通知</p>
                            <p className="text-sm text-slate-600">接收重要邮件通知</p>
                          </div>
                        </div>
                        <Switch
                          checked={settings.emailNotifications}
                          onCheckedChange={(checked) => handleSettingChange("emailNotifications", checked)}
                        />
                      </div>

                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                          <MessageSquare className="w-5 h-5 text-slate-600" />
                          <div>
                            <p className="font-medium text-slate-900">短信通知</p>
                            <p className="text-sm text-slate-600">接收短信验证码和重要通知</p>
                          </div>
                        </div>
                        <Switch
                          checked={settings.smsNotifications}
                          onCheckedChange={(checked) => handleSettingChange("smsNotifications", checked)}
                        />
                      </div>

                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                          <Globe className="w-5 h-5 text-slate-600" />
                          <div>
                            <p className="font-medium text-slate-900">营销邮件</p>
                            <p className="text-sm text-slate-600">接收产品更新和营销信息</p>
                          </div>
                        </div>
                        <Switch
                          checked={settings.marketingEmails}
                          onCheckedChange={(checked) => handleSettingChange("marketingEmails", checked)}
                        />
                      </div>
                    </div>
                  </div>
                )}

                {/* 外观设置 */}
                {activeSection === "appearance" && (
                  <div className="space-y-6">
                    <div>
                      <h2 className="text-2xl font-semibold text-slate-900 mb-6">外观设置</h2>
                    </div>

                    <div className="space-y-6">
                      <div>
                        <Label>主题</Label>
                        <div className="grid grid-cols-3 gap-4 mt-3">
                          {[
                            { value: "light", label: "浅色", icon: Sun },
                            { value: "dark", label: "深色", icon: Moon },
                            { value: "system", label: "跟随系统", icon: Smartphone },
                          ].map((theme) => {
                            const Icon = theme.icon
                            return (
                              <button
                                key={theme.value}
                                onClick={() => handleSettingChange("theme", theme.value)}
                                className={`p-4 border rounded-lg flex flex-col items-center space-y-2 transition-colors ${
                                  settings.theme === theme.value
                                    ? "border-blue-500 bg-blue-50"
                                    : "border-slate-200 hover:bg-slate-50"
                                }`}
                              >
                                <Icon className="w-6 h-6" />
                                <span className="text-sm">{theme.label}</span>
                              </button>
                            )
                          })}
                        </div>
                      </div>

                      <div>
                        <Label>字体大小</Label>
                        <Select
                          value={settings.fontSize}
                          onValueChange={(value) => handleSettingChange("fontSize", value)}
                        >
                          <SelectTrigger className="mt-2">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="small">小</SelectItem>
                            <SelectItem value="medium">中</SelectItem>
                            <SelectItem value="large">大</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium text-slate-900">紧凑模式</p>
                          <p className="text-sm text-slate-600">减少界面间距，显示更多内容</p>
                        </div>
                        <Switch
                          checked={settings.compactMode}
                          onCheckedChange={(checked) => handleSettingChange("compactMode", checked)}
                        />
                      </div>
                    </div>
                  </div>
                )}

                {/* 隐私设置 */}
                {activeSection === "privacy" && (
                  <div className="space-y-6">
                    <div>
                      <h2 className="text-2xl font-semibold text-slate-900 mb-6">隐私设置</h2>
                    </div>

                    <div className="space-y-6">
                      <div>
                        <Label>个人资料可见性</Label>
                        <Select
                          value={settings.profileVisibility}
                          onValueChange={(value) => handleSettingChange("profileVisibility", value)}
                        >
                          <SelectTrigger className="mt-2">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="public">公开</SelectItem>
                            <SelectItem value="friends">仅好友</SelectItem>
                            <SelectItem value="private">私密</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      <div className="space-y-4">
                        <div className="flex items-center justify-between">
                          <div>
                            <p className="font-medium text-slate-900">显示邮箱地址</p>
                            <p className="text-sm text-slate-600">在个人资料中显示邮箱</p>
                          </div>
                          <Switch
                            checked={settings.showEmail}
                            onCheckedChange={(checked) => handleSettingChange("showEmail", checked)}
                          />
                        </div>

                        <div className="flex items-center justify-between">
                          <div>
                            <p className="font-medium text-slate-900">显示手机号码</p>
                            <p className="text-sm text-slate-600">在个人资料中显示手机号</p>
                          </div>
                          <Switch
                            checked={settings.showPhone}
                            onCheckedChange={(checked) => handleSettingChange("showPhone", checked)}
                          />
                        </div>

                        <div className="flex items-center justify-between">
                          <div>
                            <p className="font-medium text-slate-900">数据收集</p>
                            <p className="text-sm text-slate-600">允许收集使用数据以改善服务</p>
                          </div>
                          <Switch
                            checked={settings.dataCollection}
                            onCheckedChange={(checked) => handleSettingChange("dataCollection", checked)}
                          />
                        </div>
                      </div>

                      <div className="pt-4 border-t">
                        <Button variant="outline" onClick={handleExportData} className="mr-3 bg-transparent">
                          <Download className="w-4 h-4 mr-2" />
                          导出我的数据
                        </Button>
                        <Button variant="destructive" onClick={handleDeleteAccount}>
                          <Trash2 className="w-4 h-4 mr-2" />
                          删除账户
                        </Button>
                      </div>
                    </div>
                  </div>
                )}

                {/* 安全设置 */}
                {activeSection === "security" && (
                  <div className="space-y-6">
                    <div>
                      <h2 className="text-2xl font-semibold text-slate-900 mb-6">安全设置</h2>
                    </div>

                    <div className="space-y-6">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                          <Key className="w-5 h-5 text-slate-600" />
                          <div>
                            <p className="font-medium text-slate-900">两步验证</p>
                            <p className="text-sm text-slate-600">为账户添加额外的安全保护</p>
                          </div>
                        </div>
                        <Switch
                          checked={settings.twoFactorAuth}
                          onCheckedChange={(checked) => handleSettingChange("twoFactorAuth", checked)}
                        />
                      </div>

                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                          <Bell className="w-5 h-5 text-slate-600" />
                          <div>
                            <p className="font-medium text-slate-900">登录提醒</p>
                            <p className="text-sm text-slate-600">新设备登录时发送通知</p>
                          </div>
                        </div>
                        <Switch
                          checked={settings.loginAlerts}
                          onCheckedChange={(checked) => handleSettingChange("loginAlerts", checked)}
                        />
                      </div>

                      <Separator />

                      <div className="space-y-3">
                        <h3 className="font-medium text-slate-900">密码管理</h3>
                        <Button variant="outline">
                          <Lock className="w-4 h-4 mr-2" />
                          修改密码
                        </Button>
                      </div>

                      <div className="space-y-3">
                        <h3 className="font-medium text-slate-900">活跃会话</h3>
                        <div className="space-y-2">
                          <div className="p-3 border rounded-lg">
                            <div className="flex justify-between items-center">
                              <div>
                                <p className="font-medium">当前设备</p>
                                <p className="text-sm text-slate-600">Chrome on macOS • 上海</p>
                              </div>
                              <Badge className="bg-green-100 text-green-700">当前</Badge>
                            </div>
                          </div>
                          <div className="p-3 border rounded-lg">
                            <div className="flex justify-between items-center">
                              <div>
                                <p className="font-medium">iPhone</p>
                                <p className="text-sm text-slate-600">Safari on iOS • 北京 • 2天前</p>
                              </div>
                              <Button variant="outline" size="sm">
                                注销
                              </Button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {/* 计费设置 */}
                {activeSection === "billing" && (
                  <div className="space-y-6">
                    <div>
                      <h2 className="text-2xl font-semibold text-slate-900 mb-6">订阅与计费</h2>
                    </div>

                    <div className="space-y-6">
                      <div className="p-6 border rounded-lg">
                        <div className="flex justify-between items-center mb-4">
                          <div>
                            <h3 className="font-semibold text-slate-900">当前计划</h3>
                            <p className="text-slate-600">免费版</p>
                          </div>
                          <Badge variant="outline">免费</Badge>
                        </div>
                        <p className="text-sm text-slate-600 mb-4">您正在使用免费版本，升级到专业版可获得更多功能。</p>
                        <Button>升级到专业版</Button>
                      </div>

                      <div className="space-y-4">
                        <h3 className="font-medium text-slate-900">计费历史</h3>
                        <div className="space-y-2">
                          <div className="flex justify-between items-center p-3 border rounded-lg">
                            <div>
                              <p className="font-medium">专业版月费</p>
                              <p className="text-sm text-slate-600">2024年1月1日</p>
                            </div>
                            <div className="text-right">
                              <p className="font-medium">¥99.00</p>
                              <Badge className="bg-green-100 text-green-700">已支付</Badge>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium text-slate-900">自动续费</p>
                          <p className="text-sm text-slate-600">到期时自动续费订阅</p>
                        </div>
                        <Switch
                          checked={settings.autoRenew}
                          onCheckedChange={(checked) => handleSettingChange("autoRenew", checked)}
                        />
                      </div>
                    </div>
                  </div>
                )}

                {/* 保存按钮 */}
                <div className="flex justify-end pt-6 border-t">
                  <Button onClick={handleSave}>保存设置</Button>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </main>
    </div>
  )
}
